﻿using Himp.Platform.Permissions;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Identity;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Users;

namespace Himp.Platform
{
    /// <summary>
    /// 角色权限
    /// </summary>
    [Authorize]
    public class RolePermissionService : PlatformAppService
    {
        private readonly IPermissionAppService _permissionAppService;

        public RolePermissionService(IPermissionAppService permissionAppService)
        {
            _permissionAppService = permissionAppService;
        }

        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <returns></returns>
        public async Task<PagedResultDto<string>> GetAsync()
        {
            PagedResultDto<string> resultDto = new PagedResultDto<string>();
            List<string> permissions = new List<string>();
            var providerName = "R";
            var roles = CurrentUser.Roles;

            foreach (var role in roles)
            {
                var permissionListResult = await _permissionAppService.GetAsync(providerName, role);

                permissionListResult.Groups.ForEach(group =>
                {
                    group.Permissions.ForEach(permission =>
                    {
                        if (permission.IsGranted)
                        {
                            permissions.Add(permission.Name);
                        }
                    });
                });
            }

            resultDto.Items = permissions;
            resultDto.TotalCount = resultDto.Items.Count;

            return resultDto;
        }
    }
}
